/**
 * 支持多客户端模式，由 Client 对象掌管
 */

import WebSocket from "ws";
import { log } from "../tool/log";
import { Game } from "./Game";
import { MessageType } from "./messageType";

export class Client {

    public webSocket!: WebSocket;
    constructor(private QQ: string, private verifyKey: string, private host: string = "ws://localhost:30888") {
        this.launch()
    }

    launch() {

        this.webSocket = this.linkWebSocket(this.QQ, this.verifyKey, this.host);

        const client = this;

        this.webSocket.onopen = function () {
            console.log(`${client.QQ}:连接成功`);
            // sendFriendMessage("1517607397", [MessageType.toPlain("hello world")]);
            // sendGroupMessage("383968751", [MessageType.toPlain("hello world")]);
        }

        const that = this;
        this.webSocket.onclose = function () {
            console.error(`${client.QQ}:连接断开，尝试重新连接。`,);
            that.launch()
        }

        this.webSocket.onmessage = function (data) {
            // 将收到的字符串转换成 对象
            const message = JSON.parse(data.data.toString()).data as unknown as MessageType

            

            // 判断消息类型必须使群消息
            if (message.type === "GroupMessage") {
                /** 日志 */
                log(message)
                /** 群 ID */
                const groupId = message.sender.group.id.toString();
                /** 命令 */
                const commandText = MessageType.toCommand(message.messageChain)

                // 开始游戏
                if (!Game.hasGame(groupId)) {
                    if (commandText.trim() === '开始游戏') {
                        new Game(client, message.sender.group.id.toString())
                        return; // 终止
                    }
                }
                // 结束游戏 
                if (message.sender.permission === "OWNER" && Game.hasGame(groupId)) {
                    if (commandText.trim() === '结束游戏') {
                        Game.killGame(groupId)
                        return;// 终止
                    }
                }

                // 帮助命令
                if (["帮助", "help"].indexOf(commandText) >= 0) {
                    client.sendGroupMessage(groupId, [
                        MessageType.toAt(message.sender.id),
                        MessageType.toPlain("请参考:https://gitee.com/catchcode/qq-role-game\n记着点亮右上角的Star哦。"),
                    ])
                }

                // 执行指令
                if (Game.hasGame(groupId)) {
                    const game = Game.getGame(groupId);
                    game.excute(`${message.sender.id} ${message.sender.memberName} ${commandText}`);
                }
            }

        }
    }

    linkWebSocket(QQ: string, verifyKey: string, host: string = "ws://localhost:30888") {
        let ws: WebSocket
        for (let i = 1; i <= 3; i++) {
            try {
                ws = new WebSocket(`${host}/message?verifyKey=${verifyKey}&qq=${QQ}`)
                return ws;
            } catch (e) {
                console.error((e as Error).message)
                console.log(`${QQ} 连接失败，进行第${i}次尝试。`)
            }
        }
        console.error("WebSocket 没有连接上服务器端，程序终止。")
        process.exit()
    }

    sendGroupMessage(groupId: string, messageChain: MessageType[]) {
        // console.log(JSON.stringify(messageChain))
        this.webSocket.send(JSON.stringify({
            "syncId": 123,                  // 消息同步的字段
            "command": "sendGroupMessage", // 命令字
            "subCommand": null,             // 子命令字, 可空
            "content": {// 命令的数据对象, 与通用接口定义相同
                "target": groupId,
                "messageChain": messageChain
            }
        }))
    }

    sendFriendMessage(qq: string, messageChain: MessageType[]) {
        this.webSocket.send(JSON.stringify({
            "syncId": 123,                  // 消息同步的字段
            "command": "sendFriendMessage", // 命令字
            "subCommand": null,             // 子命令字, 可空
            "content": {// 命令的数据对象, 与通用接口定义相同
                "target": qq,
                "messageChain": messageChain
            }
        }))
    }

    TempMessage(qq: string, groupId: string, messageChain: MessageType[]) {
        this.webSocket.send(JSON.stringify({
            "syncId": 123,                  // 消息同步的字段
            "command": "TempMessage", // 命令字
            "subCommand": null,             // 子命令字, 可空
            "content": {// 命令的数据对象, 与通用接口定义相同
                "qq": qq,
                "group": groupId,
                "messageChain": messageChain
            }
        }))
    }
}